package cn.net.dpi.core.trace;

import lombok.Data;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 基于 {@link MetaTrace}
 * 该类方便自己构造全生命周期的链路信息，对外展示或者持久化等
 *
 * @author dangzhicairang
 */
@Data
public class CompositeTrace implements TraceOuter {

    private String name;

    private List<MetaTrace> traces = new ArrayList<>();

    public CompositeTrace() {
    }

    public CompositeTrace(String name) {
        this.name = name;
    }

    public CompositeTrace addTrace(MetaTrace metaTrace) {
        this.traces.add(metaTrace);
        return this;
    }

    public MetaTrace newTrace(String name) {
        return this.newTrace(name, this.name);
    }

    public MetaTrace newTrace(String name, String traceId) {
        MetaTrace metaTrace = new MetaTrace(name, traceId);
        this.addTrace(metaTrace);
        return metaTrace;
    }

    @Override
    public String prettyOut(Logger logger) {

        String arrow = "            |\n" +
                       "            v\n";
        StringBuilder sb = new StringBuilder();
        sb.append("\n");

        for (int i = 0; i < this.traces.size(); i ++) {
            sb.append(this.traces.get(i).prettyOut());
            if (i != this.traces.size() - 1) {
                sb.append(arrow);
            }
        }

        return sb.toString();
    }
}
